from steam.client import SteamClient
from dota2.client import Dota2Client
from dota683_ladder.models import Game, Player
from dota2.proto_enums import EMatchOutcome
from pprint import pprint
import time
from .email import getCode

USERNAME="bobo1993324_2"
PASSWORD=""


client = SteamClient()
dota = Dota2Client(client)

@client.on('logged_on')
def start_dota():
    dota.launch()

@dota.on('ready')
def do_dota_stuff():
    print("dota ready")
    #TODO get match ids from DB in init state and begins within 2 hours
    games = Game.objects.filter(state = "IN")
    matchIds = []
    for game in games:
        matchIds.append(game.gameid)
    print(matchIds)
    jobId = dota.request_matches_minimal(matchIds)
    print("Request job " + jobId)
    response = dota.wait_msg(jobId, timeout = 120)
    print(response)
    if (response.matches and len(response.matches) > 0):
        matches = response.matches
        print("matches size " + str(len(matches)))
        for one_match in matches:
            print("Match {} result: {}".format(one_match.match_id, one_match.match_outcome))

            radiant_gain = 0
            dire_gain = 0
            if (one_match.match_outcome == EMatchOutcome.RadVictory):
                radiant_gain = 25
                dire_gain = -25
            elif (one_match.match_outcome == EMatchOutcome.DireVictory):
                radiant_gain = -25
                dire_gain = 25

            #TODO validate player count
            #TODO validate map name from detailed match data

            for player in one_match.players:
                try:
                    player_record = Player.objects.get(steamid = player.account_id)
                except Player.DoesNotExist:
                    print("New player {}".format(player.account_id))
                    player_record = Player.objects.create(steamid = player.account_id)

                player_old_score = player_record.score
                if (player.player_slot <= 4):
                    player_record.score = player_record.score + radiant_gain
                else:
                    player_record.score = player_record.score + dire_gain
                print("Player {} score change from {} to {}".format(player_record.steamid, player_old_score, player_record.score))
                player_record.save()

            game_record = Game.objects.get(gameid = one_match.match_id)
            game_record.state = "PR"
            game_record.save()
            print("processed game " + str(game_record.gameid))
    else:
        print("ERROR:No matches found")
        #TODO for not found matches, if time passed certain length, then move game to ERROR state
    exit(0)

#@client.on(client.EVENT_AUTH_CODE_REQUIRED)
def auth_code_prompt(is_2fa, code_mismatch):
    print("Waiting 30 seconds for email to reach imap server.")
    print(code_mismatch)
    #time.sleep(5)
    code = input()#getCode()
    print(code)
    print(type(code))
    result = client.login(USERNAME, PASSWORD, None, code, None)
    return result

result = client.login(username=USERNAME, password=PASSWORD)
print(result)
print("Waiting 30 seconds for email to reach imap server.")
time.sleep(10)
code = getCode()
result = client.login(USERNAME, PASSWORD, None, code, None)
print(result)
client.run_forever()
